Vue.component('small-map', {
    template: '<div id="smallMap" style="width:100%;height:100%" ></div>',
    props: ['options', 'pointInfo', 'optiona', 'draw'],
    data: function () {
        return {
            message: 'map',
            centerPoint: null,
            map: null,
            centX: 121.274063,
            centY: 37.503843,
            existedObj: [],
            landmarksInObj: [],
            landmarksOutObj: [],
            landmarksHotObj: [],
            sequenceObj: [],
            inPNG: 'wifiin.png',
            outPNG: 'wifi.png',
            hotPNG: 'fence.png',
            outputPath: '../js/map/',
            minLevel: 11,
            maxLevel: 18,
            dist:0.0035,        
            format: '.png',
            walkTimer: null,
            tileLayer: null,
            areaOverlays: []
        }
    },
    mounted: function () {
        var self = this
        self.tileLayer = new BMap.TileLayer();

        self.tileLayer.getTilesUrl = function (tileCoord, zoom) {
            var x = tileCoord.x;
            var y = tileCoord.y;
            var url = self.outputPath + zoom + '/' + x + '/' + y + self.format;
            // console.log(outputPath+zoom)
            return url;
        }
        var MyMap = new BMap.MapType('MyMap', self.tileLayer, {
            minZoom: this.minLevel,
            maxZoom: this.maxLevel
        });
        self.map = new BMap.Map('smallMap', {
            mapType: MyMap
        });
        self.map.enableScrollWheelZoom();
        self.map.centerAndZoom(new BMap.Point(self.centX, self.centY), 15);
        var icon = new BMap.Icon('../assets/img/wifi.png', new BMap.Size(64, 64));
        var p = new BMap.Point(this.centX, this.centY);
        var marker = new BMap.Marker(p, {
            icon: icon,
            enableClicking: false,
            enableDragging: false
        });
        this.map.addOverlay(marker);
        //移除百度logo
        setTimeout(function () {
            $('.anchorBL, .BMap_cpyCtrl').remove();
        }, 200);
       

       

       
        // console.log(point1)
        var overlaycomplete = function (e) {
            var poly = e.overlay
            // console.log(e.overlay)
            switch (e.drawingMode) {
                case 'circle':
                    for (var i in point1) {
                        // console.log(BMapLib.GeoUtils.isPointInCircle(point1[i], poly))
                        if (BMapLib.GeoUtils.isPointInCircle(point1[i], poly)) {
                            console.log(point1[i])
                        };
                    }
                    break;
                case 'polygon':
                    for (var i in point1) {
                        // console.log(BMapLib.GeoUtils.isPointInPolygon(point1[i], poly))
                        if (BMapLib.GeoUtils.isPointInPolygon(point1[i], poly)) {
                            console.log(point1[i])
                        };
                    }
                    break;
                case 'rectangle':
                for (var i in point1) {
                    alert(1)
                    // console.log(BMapLib.GeoUtils.isPointInRect(point1[i], poly.Mu))
                    if (BMapLib.GeoUtils.isPointInRect(point1[i], poly.Mu)) {
                        console.log(point1[i])
                    };
                }
                break;
                case 'polyline':
                for (var i in point1) {
                    // console.log(BMapLib.GeoUtils.isPointOnPolyline(point1[i], poly))
                    if (BMapLib.GeoUtils.isPointOnPolyline(point1[i], poly)) {
                        console.log(point1[i])
                    };
                }
                break;
            }
            self.areaOverlays.push(e.overlay);
        };
        if (self.draw === '1') {
            let styleOptions = {
                strokeColor: "red", //边线颜色。
                fillColor: "red", //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 10, //边线的宽度，以像素为单位。
                strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
                fillOpacity: 0.6, //填充的透明度，取值范围0 - 1。
                strokeStyle: 'solid' //边线的样式，solid或dashed。
            }
            this.drawingManager = new BMapLib.DrawingManager(this.map, {
                isOpen: false, //是否开启绘制模式
                enableDrawingTool: true, //是否显示工具栏
                drawingToolOptions: {
                    anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                    offset: new BMap.Size(5, 5), //偏离值
                },
                circleOptions: styleOptions, //圆的样式
                polylineOptions: styleOptions, //线的样式
                polygonOptions: styleOptions, //多边形的样式
                rectangleOptions: styleOptions //矩形的样式
            });
            //添加鼠标绘制工具监听事件，用于获取绘制结果
            this.drawingManager.addEventListener('overlaycomplete', overlaycomplete)
        }
        //this.showRoute()
        //加入单个地标，pointStr="X$Y$地标说明", activate为是否立刻激活地标

        // var route1=[[this.centX,this.centY],[121.280,37.516],[121.290,37.536],[121.273,37.526],[121.260,37.533]];
        // var route2=[[this.centX,this.centY],[121.280,37.516],[121.290,37.536],[121.288,37.526],[121.279,37.541],[121.273,37.526]];
        // var dot = [[121.288,37.526],[121.279,37.541]];
        // var route = []
        // var routede = []
        // for(var i=0;i<1500;i++)
        // {
        //     route.push([route1[i%4][0]+(i/10000),route1[i%4][1]+(i/10000)])
        //     // addLine(route2,"red")
        // }
        // for(var i=0;i<route.length;i++)
        // {
        //     addLandmark([route[i][0],route[i][1],'侧'],inPNG,function(m){
        //     });
        // }
        // addLine(route2,"red")

        // for(var i=0;i<dot.length;i++)
        // {
        //     addLandmark([dot[i][0],dot[i][1]],inPNG,function(m){

        //     });
        // }
        // function deletePoint(){
        //     var allOverlay = map.getOverlays();
        //     for(var i = 0;i<allOverlay.length;i++) {
        //         //删除指定经度的点
        //         for(var j=0;j<routede.length;j++){
        //             // console.log(allOverlay[i])
        //             if (allOverlay[i].getPosition().lng == routede[j]) {
        //                 map.removeOverlay(allOverlay[i]);
        //                // return false;
        //             }
        //         }


        //     }

        // }
        // setTimeout(function(){
        //     deletePoint()
        // },5000)
        // function resetPeopleLocation(step)
        // {	
        // 	// console.log(flag,f)
        // 	var s = step
        // 	// if(flag && f == undefined) return;
        // 	if(s>=sequence.length) return;
        // 	// console.log(step)
        // 	walkTimer = setInterval(()=>{
        // 		peopleMarker.setPosition(sequence[s]);
        // 		s++
        // 	},50)

        // 	// setTimeout(function(){resetPeopleLocation(step+1);},50);
        // }
        // function calculateSequence(start, end) {
        // 	var x0=parseFloat(start.lng);
        // 	var y0=parseFloat(start.lat);
        // 	var x1=parseFloat(end.lng);
        // 	var y1=parseFloat(end.lat);
        // 	var angle=0.0;
        // 	var oldDistance, newDistance;

        // 	//debugger;

        // 	if(x1!=x0) {
        // 		var quotient=(y1-y0)/(x1-x0);
        // 		angle=Math.atan(quotient)*180/ Math.PI;

        // 		if(x0>x1) angle=angle-180;
        // 		if(angle<0) angle=angle+360;
        // 		//console.log("quotient="+quotient);
        // 		//console.log("angle="+angle);
        // 		//debugger;

        // 	}
        // 	else {
        // 		if(y1>y0) angle=90;
        // 		else angle=-90;
        // 		debugger;
        // 	}


        // 	oldDistance=(y1-y0)*(y1-y0)+(x1-x0)*(x1-x0);
        // 	while(1)
        // 	{
        // 		x0=x0+speed*Math.cos(angle* Math.PI/180.0);
        // 		y0=y0+speed*Math.sin(angle* Math.PI/180.0);
        // 		sequence.push(new BMap.Point(x0,y0));

        // 		newDistance=(y1-y0)*(y1-y0)+(x1-x0)*(x1-x0);

        // 		if(isNaN(newDistance) || newDistance>oldDistance) 
        // 			{   //debugger; 
        // 				break;  }

        // 		oldDistance=newDistance;
        // 	}

        // 	console.log(sequence.length+",");

        // }
        // movePeople()

    },
    methods: {
        resetPeopleLocation: function (step) {
            // console.log(flag,f)
            var s = step
            // if(flag && f == undefined) return;
            if (s >= sequence.length) return;
            // console.log(step)
            this.walkTimer = setInterval(() => {
                peopleMarker.setPosition(sequence[s]);
                s++
            }, 50)
            // setTimeout(function(){resetPeopleLocation(step+1);},50);
        },
        calculateSequence: function (start, end) {
            var speed = 0.0001;
            var x0 = parseFloat(start.lng);
            var y0 = parseFloat(start.lat);
            var x1 = parseFloat(end.lng);
            var y1 = parseFloat(end.lat);
            var angle = 0.0;
            var oldDistance, newDistance;

            //debugger;

            if (x1 != x0) {
                var quotient = (y1 - y0) / (x1 - x0);
                angle = Math.atan(quotient) * 180 / Math.PI;

                if (x0 > x1) angle = angle - 180;
                if (angle < 0) angle = angle + 360;
                //console.log("quotient="+quotient);
                //console.log("angle="+angle);
                //debugger;

            } else {
                if (y1 > y0) angle = 90;
                else angle = -90;
                debugger;
            }


            oldDistance = (y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0);
            while (1) {
                x0 = x0 + speed * Math.cos(angle * Math.PI / 180.0);
                y0 = y0 + speed * Math.sin(angle * Math.PI / 180.0);
                sequence.push(new BMap.Point(x0, y0));

                newDistance = (y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0);

                if (isNaN(newDistance) || newDistance > oldDistance) { //debugger; 
                    break;
                }

                oldDistance = newDistance;
            }

            console.log(sequence.length + ",");
        },

        mapRefresh: function () {
            map.centerAndZoom(centerPoint, 18);
        },
        toggleManyLandmarks: function (type) {
            var png, obj;
            //map.clearOverlays(); 
            switch (type) {
                case 1:
                    png = inPNG;
                    obj = landmarksInObj;
                    break;
                case 2:
                    png = outPNG;
                    obj = landmarksOutObj;
                    break;
                case 3:
                    png = hotPNG;
                    obj = landmarksHotObj;
                    break;
            }

            //debugger;

            // if show all landmarks
            if (obj.length <= 0) {

                for (var i = 1; i <= 20; i++) {
                    var newx = Math.random() / (0.5 / this.dist) - this.dist + this.centX;
                    var newy = Math.random() / (0.5 / this.dist) - this.dist + this.centY;
                    this.addLandmark([newx, newy, "null"], png, function (m) {
                        obj.push(m);
                        var r = Math.random() * 2000;
                        setTimeout(function () {
                            m.setAnimation(BMAP_ANIMATION_BOUNCE);
                        }, r);
                        setTimeout(function () {
                            m.setAnimation();
                        }, r + 4000);

                    });

                    //console.log("add:"+info[0]+","+info[1]);
                    //跳动的动画
                }
            }

            //if clear all landmarks
            else if (obj.length > 0) {
                for (var i = 0; i < obj.length; i++) {
                    //debugger;
                    map.removeOverlay(obj[i]);
                }
                if (type == 1) landmarksInObj = [];
                if (type == 2) landmarksOutObj = [];
                if (type == 3) landmarksHotObj = [];
            }
        },
        addLandmark: function (info, iconImg, callback) {

            //var info = pointStr.split('$');
            // 创建信息窗口对象

            var icon = new BMap.Icon('../assets/img/' + iconImg, new BMap.Size(48, 48), {
                anchor: new BMap.Size(15, 15)
            });
            var p = new BMap.Point(parseFloat(info[0]), parseFloat(info[1]));
            var marker = new BMap.Marker(p, {
                icon: icon
            });

            if (info[2]) {
                var infoWindow = new BMap.InfoWindow(info[2], {
                    width: 350
                });
                marker.addEventListener("click", function () {
                    this.openInfoWindow(infoWindow);
                    $(".btn-group > .btn").click(function () {
                        $(this).addClass("active").siblings().removeClass("active");
                    });
                });
            }
            this.map.addOverlay(marker);
            if (callback) callback(marker);

            //立刻激活地标
            //if(activate) $(marker.F).trigger('click');

            //setTimeout(function(){map.panTo(p,{noAnimation:false});},500);
        },
        addSequenceMark: function (info, seq, callback) {
            this.addLandmark(info, 'smallSunshine.gif', callback);
            var myLabel = new BMap.Label(seq + "", {
                offset: new BMap.Size(-2, -20),
                position: new BMap.Point(info[0], info[1])
            });
            myLabel.setStyle({
                "color": "red", //颜色
                "fontSize": "24px", //字号
                "padding": "0",
                "fontWeight": "bold",
                "border": "0px", //边
                "textAlign": "center", //文字水平居中显示
                "lineHeight": "48px", //行高，文字垂直居中显示
                "cursor": "pointer"
            });

            this.map.addOverlay(myLabel);
        },
        addLabel: function (info, label, callback) {
            var myLabel = new BMap.Label(label, {
                offset: new BMap.Size(-15, 8),
                position: new BMap.Point(info[0], info[1])
            });
            myLabel.setStyle({

                "color": "red", //颜色
                "fontSize": "16px", //字号
                "padding": "0",
                "fontWeight": "bold",
                "border": "1px", //边
                "textAlign": "center", //文字水平居中显示
                "lineHeight": "24px", //行高，文字垂直居中显示
                "cursor": "pointer",
                "backgroundColor": "white"
            });

            this.map.addOverlay(myLabel);
            if (callback) callback(myLabel);
        },
        addLine: function (info, color, callback) {
            var ar = [];
            for (var i = 0; i < info.length; i++) {
                ar.push(new BMap.Point(info[i][0], info[i][1]));
            }
            var polyline = new BMap.Polyline(ar, {
                strokeColor: color,
                strokeWeight: 3,
                strokeStyle: "dashed",
                strokeOpacity: 0.2
            });

            this.map.addOverlay(polyline);
            if (callback) callback(polyline);
            return polyline
        },
        deleteLine: function (polyline) {
            polyline.forEach(val => {
                this.map.removeOverlay(val)
            })
        },
        addLineBD: function (info, color, callback) {
            var polyline = new BMap.Polyline(info, {
                strokeColor: color,
                strokeWeight: 3,
                strokeStyle: "dashed",
                strokeOpacity: 0.8
            });
            this.map.addOverlay(polyline);
            if (callback) callback(polyline);
        },
        showRoute: function () {
            var self = this
            var c = 2
            // console.log(self.optiona.chooseoption)
            if (c >= 2) {

                for (var i = 0; i < self.optiona.chooseoption.length; i++) {
                    self.addSequenceMark([self.optiona.chooseoption[i][0], self.optiona.chooseoption[i][1], "路径1，地点" + (i + 1)], i + 1, function (m) {
                        console.log(m)
                        self.sequenceObj.push(m);
                    });
                    self.addLine(self.optiona.chooseoption, "red")
                    // line1.push(addLine(route1,"red"))
                }
                var route2 = [
                    [121.274, 37.517],
                    [121.290, 37.506],
                    [121.263, 37.540],
                    [121.285, 37.536]
                ];
                for (var i = 0; i < route2.length; i++) {
                    self.addSequenceMark([route2[i][0], route2[i][1], "路径2，地点" + (i + 1)], i + 1, function (m) {
                        self.sequenceObj.push(m);
                    });
                    self.addLine(route2, "green")
                    // line2.push(addLine(route2,"green"));
                }
                // deleteLine(line1)
                // toggle_rightbar();
            } else if (c === 1) {
                var route1 = [
                    [self.centX, self.centY],
                    [121.280, 37.516],
                    [121.290, 37.536],
                    [121.273, 37.526],
                    [121.260, 37.533]
                ];

                for (var i = 0; i < route1.length; i++) {
                    self.addSequenceMark([route1[i][0], route1[i][1], "路径1，地点" + (i + 1)], i + 1, function (m) {
                        self.sequenceObj.push(m);
                    });
                    self.addLine(route1, "red")
                    // line1.push(addLine(route1,"red"))
                }
            }
        },
        movePeople: function (route1) {
            let self = this
            this.landmarksInObj = []
            this.existedObj.forEach(val => {
                this.map.removeOverlay(val)
                delete val
            })
            this.existedObj = []
            var rout1copy = []
            var speed = 0.0001;
            rout1copy = route1.map(val => {
                return new BMap.Point(val[0], val[1])
            })
            // if(sequence.length>0) {this.changePeople();return;}
            // this.toggleManyLandmarks(1);
            // for (var i = 0; i < 20; i++) {
            //     shown.push(landmarksInObj[i]);
            // }
            // var l = shown.length;
            // var second, third, fourth;

            sequence = [];
            // second= shown[Math.floor(l / 4.0)].point;
            // third= shown[Math.floor(2*l / 4.0)].point;
            // fourth= shown[Math.floor(3*l / 4.0)].point;
            var startPoint = rout1copy[0]
            var endPoint = rout1copy[rout1copy.length - 1]
            this.addLineBD(rout1copy, "green", function (c) {
                self.existedObj.push(c);
            });
            this.addLandmark([startPoint.lng, startPoint.lat], "smallSunshine.gif", function (c) {
                self.existedObj.push(c);
            });
            this.addLandmark([endPoint.lng, endPoint.lat], "smallSunshine.gif", function (c) {
                self.existedObj.push(c);
            });

            var icon = new BMap.Icon('../assets/img/walking.gif', new BMap.Size(128, 128), {
                anchor: new BMap.Size(64, 80)
            });
            peopleMarker = new BMap.Marker(startPoint, {
                icon: icon
            });

            this.map.addOverlay(peopleMarker);
            self.existedObj.push(peopleMarker);
            // setTimeout(function(){peopleMarker.setAnimation(BMAP_ANIMATION_DROP);},100);
            // setTimeout(function(){peopleMarker.setAnimation();},1000);


            // calculateSequence(startPoint, second);
            // calculateSequence(second, third);
            // calculateSequence(third, fourth);
            // calculateSequence(fourth, endPoint);
            for (var i = 0; i < rout1copy.length - 1; i++) {
                this.calculateSequence(rout1copy[i], rout1copy[i + 1]);
            }

            //debugger; 
            clearInterval(this.walkTimer)
            this.resetPeopleLocation(0);
        },
        deleteRoute: function (cma) {
            var allOverlay = this.map.getOverlays();
            //  console.log(allOverlay)
            for (var i = 0; i < allOverlay.length; i++) {
                //删除指定经度的点
                //console.log(allOverlay[i].toString())
                for (var j = 0; j < cma.length; j++) {
                    if (allOverlay[i].toString() === '[object Marker]') {
                        if (allOverlay[i].point.lng == cma[j][0]) {
                            this.map.removeOverlay(allOverlay[i])
                        }
                    }
                }
            }
        },
        addpmarker: function (nval) {
            for (var i = 0; i < nval.length; i++) {
                this.addLandmark([nval[i][0], nval[i][1], '侧'], this.inPNG, function (m) {});
            }
        },
        removemovePeople() {
            this.existedObj.forEach(val => {
                this.map.removeOverlay(val)
                delete val
            })
            this.existedObj = []
        },
        clearAll: function () {
            for (var i = 0; i < this.areaOverlays.length; i++) {
                this.map.removeOverlay(this.areaOverlays[i])
            }
            this.areaOverlays.length = 0
        }
    },
    watch: {
        'optiona.chooseoption': function (newVal, oldVal) {
            this.addpmarker(newVal)
        },
        'optiona.chooseoptionfalse': function (newVal, oldVal) {
            this.deleteRoute(newVal)
        },
        'optiona.peopoleoption': function (newVal, oldVal) {
            this.map.removeOverlay(this.existedObj)
            this.movePeople(newVal)
        },
        'areaOverlays': function (newVal, oldVal) {
            // console.log(newVal)
        }
    }
})